package com.zzptc.easyshop.servlet;

import com.zzptc.easyshop.dao.GoodTypeDaoImp;
import com.zzptc.easyshop.dao.IDAO;
import com.zzptc.easyshop.dao.ProductDao;
import com.zzptc.easyshop.util.ShopCarUtil;
import com.zzptc.easyshop.vo.Product;
import com.zzptc.easyshop.vo.ShopCar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ShopCartServlet")
public class ShopCartServlet extends HttpServlet {
    List<ShopCar> carlist;//全局变量
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");

         //获取id
        int id=Integer.parseInt(request.getParameter("shopid"));
        ProductDao dao=new ProductDao();
        Product product=null;
        System.out.println(id);
        try {
            product=dao.getProductByid(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(product.getEp_name());
        ShopCar shopCar=new ShopCar();
        shopCar.setEp_id(id);
        shopCar.setEp_name(product.getEp_name());
        shopCar.setEp_price(product.getEp_price());
        shopCar.setPicture(product.getEp_file_name());
        shopCar.setSum(1);
        //防止重复new（覆盖）   保证只有一台购物车

        if(carlist==null){
            carlist=new ArrayList();
        }
        //将商品添加到购物车(如果第一次添加 直接add；如果不是第一次添加，就只要将数量加1)
        ShopCarUtil.addGood(shopCar,carlist);
        //传输数据
        HttpSession se=request.getSession();
        se.setAttribute("shop",carlist);
       // session.setAttribute("carlist",carlist);
        //request.getRequestDispatcher("shopping.jsp").forward(request,response);
        response.sendRedirect("shopping.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
